<!--
 * @Descripttion: 身份发行-新建/编辑
 * @Author: 何伟伦 weilun@ssc-hn.com
 * @Date: 2024-03-27
 * @LastEditors: 何伟伦 weilun@ssc-hn.com
 * @LastEditTime: 2024-05-17
-->
<script lang="ts" setup>
  import { ArrowLeftOutlined, CloseOutlined } from '@ant-design/icons-vue'
  import { onMounted, onUnmounted, reactive, ref, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import { requestGetIdentityInfoById, requestSaveIdentityInfo } from '/@/api/business/identity'
  import { requestGetAuthTemplateList } from '/@/api/business/identity/template'
  import { requestTemplateForm } from '/@/api/content/survey/unAuth/api/json/app/config'
  import { HttpCodeEnum } from '/@/enums/httpEnum'

  const router = useRouter()
  const route = useRoute()
  const loading = ref<boolean>(false)
  const { id } = route.query

  const formRef = ref()
  const formState = ref<any>({
    identityTemplateType: null,
    identityTemplateId: null,
    identityName: '',
    identityDescription: null,
    identityStatus: 2,
    identityTemplateExample: [],
  })

  const templateParams = reactive({
    paperId: null,
    identityId: null,
  })
  const current = ref<number>(0)
  const postTime = ref<number>(0)

  const stripHtmlTags = (htmlString) => {
    // 创建一个临时的DOM元素
    const tempDiv = document.createElement('div')
    // 将HTML字符串设置为元素的内容
    tempDiv.innerHTML = htmlString
    // 使用textContent属性获取纯文本内容
    return tempDiv.textContent || tempDiv.innerText || ''
  }

  /**
   * 根据模板id请求模板表单
   */
  const initTemplateForm = async (value) => {
    const { responseData, responseCode } = await requestTemplateForm({ templateFormId: value })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      const { questions } = responseData
      formState.value.identityTemplateExample = questions.map((item) => {
        return { ...item, name: stripHtmlTags(item.questionName), value: null }
      })
    }
  }

  /**
   * 选择模板后回调
   */
  const templateIdChange = async (value, option) => {
    console.log(value, option)
    const { key } = option
    initTemplateForm(key)
  }

  /**
   * 监听模板列表选择
   */
  watch(
    () => formState.value.identityTemplateType,
    (newVal, oldVal) => {
      if (newVal !== oldVal) initTemplateType(newVal, oldVal)
    },
  )

  const rules = {
    identityTemplateType: [{ required: true, message: '请选择应用类型' }],
    identityTemplateId: [{ required: true, message: '请选择模板' }],
    identityName: [{ required: true, message: '请输入身份凭证名称' }],
    identityDescription: [{ required: true, message: '请输入身份介绍' }],
  }
  const tipsVisible = ref<boolean>(true)
  const templateList = ref<{ id: string; templateName: string; templateFormId: string }[]>([])
  const steps = ref<Array<{ title: string; url?: string }>>([{ title: '填写身份模版信息' }, { title: '创建凭证申请条件', url: `/web/question/page` }, { title: '完成审批流程', url: `/web/process/process-config` }])
  /**
   * 根据类型请求模板列表
   */
  const initTemplateType = async (value, oldVal) => {
    const { responseData, responseCode } = await requestGetAuthTemplateList({ templateType: value })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      if (oldVal !== null) formState.value.identityTemplateId = null
      templateList.value = responseData
    }
  }
  /**
   * 下一步
   */
  const nextStep = () => {
    console.log(current.value)
    formRef.value.validate().then(async () => {
      loading.value = true
      const { responseData, responseCode } = await requestSaveIdentityInfo({ ...formState.value, identityTemplateExample: JSON.stringify(formState.value.identityTemplateExample), id: id as string })
      loading.value = false
      if (responseCode === HttpCodeEnum.SUCCESS) {
        const { identityPaperId, id } = responseData
        templateParams.paperId = identityPaperId
        templateParams.identityId = id
        if (!current.value) {
          current.value++
        }
      }
    })
  }
  /**
   * iframe通信方法
   */
  const postFrame = () => {
    const myframe = document.getElementById('childFrame') as HTMLIFrameElement //获取iframe
    console.log('给iframe传参', templateParams.paperId, templateParams.identityId, myframe?.contentWindow)
    if (myframe.contentWindow) myframe.contentWindow.postMessage({ paperId: templateParams.paperId, identityId: templateParams.identityId }, '*')
  }
  /**
   * 说明提示区隐藏
   */
  const closeTips = () => {
    tipsVisible.value = !tipsVisible.value
  }
  /**
   * 回退页面，内嵌iframe后router.back异常
   */
  const pageBack = () => {
    router.replace({
      path: '/idmanage/publish/list',
    })
  }
  /**
   * 获取身份详情（编辑）
   */
  const getDetail = async () => {
    const { responseCode, responseData } = await requestGetIdentityInfoById({
      id: id as string,
    })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      const { identityTemplateType, identityTemplateId, identityName, identityDescription, identityTemplateExample, identityPaperId, id } = responseData
      formState.value.identityDescription = identityDescription
      formState.value.identityTemplateType = identityTemplateType
      formState.value.identityTemplateId = identityTemplateId
      formState.value.identityName = identityName
      formState.value.identityTemplateExample = identityTemplateExample ? JSON.parse(identityTemplateExample) : []
      templateParams.paperId = identityPaperId
      templateParams.identityId = id
    }
  }

  onMounted(() => {
    if (id) getDetail()
    window.addEventListener(
      'message',
      (e) => {
        handleMessage(e)
      },
      false,
    )
  })

  /**
   * 监听iframe
   */
  const handleMessage = (e) => {
    const { type, timeStamp } = e.data
    console.log('触发--------', postTime, timeStamp)
    if (postTime.value && Number(timeStamp) === postTime.value) {
      return
    } else if (timeStamp && postTime.value !== timeStamp) {
      postTime.value = timeStamp
    }
    const iframeDom = document.getElementById('childFrame') as HTMLIFrameElement
    const iframeSrc = iframeDom.src
    // 第二步
    if (type === 'next' && iframeSrc.includes('/question/page')) {
      current.value = 2
    } else if (type === 'next' && iframeSrc.includes('process/process-config')) {
      // 第三步
      pageBack()
    } else if (type === 'back' && iframeSrc.includes('/question/page')) {
      current.value = 0
    } else if (type === 'back' && iframeSrc.includes('/process/process-config')) {
      // 第三步
      current.value = 1
    }
  }
  /**
   * 卸载postMessage
   */
  onUnmounted(() => {
    window.removeEventListener('message', handleMessage, false)
  })
</script>

<template>
  <div class="idmanage-list-add">
    <div class="add-header">
      <arrow-left-outlined :style="{ 'font-weight': 'bold', 'margin-right': '18px' }" @click="pageBack()" />
      <span>{{ id ? '编辑' : '新增' }}身份凭证</span>
    </div>
    <a-divider />
    <div class="add-form-box">
      <div class="add-content">
        <a-steps v-model:current="current">
          <a-step v-for="item in steps" :key="item.title" :title="item.title" />
        </a-steps>
        <div class="idmanage-container">
          <div class="idmanage-tips" v-if="tipsVisible">
            <div class="tips-header">
              <div class="tips-left"><div class="tips-title"></div>说明：</div>
              <close-outlined class="tip-close" @click="closeTips" />
            </div>
            <div class="tips-content">
              <div>1、请先选择模版类型;</div>
              <div>2、填写发行的凭证信息;</div>
              <div>3、如有疑问请直接联系:13300001111。</div>
            </div>
          </div>
          <a-form v-if="current === 0" :model="formState" :rules="rules" layout="vertical" ref="formRef" name="add_form" labelAlign="left">
            <a-form-item label="模板类型" name="identityTemplateType" :rules="[{ required: true, message: '请选择模板类型' }]">
              <a-select v-model:value="formState.identityTemplateType" placeholder="请选择模板类型">
                <a-select-option :value="0">个人身份</a-select-option>
                <a-select-option :value="1">机器设备</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item v-if="formState.identityTemplateType !== null" label="模板列表" name="identityTemplateId" :rules="[{ required: true, message: '请选择模板' }]">
              <a-select v-model:value="formState.identityTemplateId" placeholder="请选择模板" @change="templateIdChange">
                <a-select-option v-for="item in templateList" :key="item.templateFormId" :value="item.id">{{ item.templateName }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="身份名称" name="identityName" :rules="[{ required: true, message: '请输入身份名称' }]">
              <a-input v-model:value="formState.identityName" allow-clear />
            </a-form-item>
            <a-form-item label="身份介绍" name="identityDescription" :rules="[{ required: true, message: '请输入身份介绍' }]">
              <a-textarea :rows="3" v-model:value="formState.identityDescription" allow-clear showCount :maxlength="150" />
            </a-form-item>
          </a-form>
          <a-row v-if="current === 0" :gutter="16">
            <a-col v-for="item in formState.identityTemplateExample" :key="item.questionId" :span="12">
              <a-form-item :label="item.name" :name="'question' + item.questionId">
                <a-input v-model:value="item.value" allow-clear />
              </a-form-item>
            </a-col>
          </a-row>
          <iframe :style="{ height: current ? '530px' : 0 }" id="childFrame" class="iframe" width="100%" frameborder="no" scrolling="no" :src="steps[current].url" @load="postFrame()"></iframe>
          <div class="btn-wrap">
            <a-space>
              <a-button :loading="loading" v-if="!current" type="primary" html-type="submit" @click="nextStep">下一步</a-button>
              <a-button :loading="loading" v-if="current === 0" type="default" html-type="submit" @click="pageBack()">取消</a-button>
            </a-space>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .idmanage-list-add {
    background: #fff;
    padding-bottom: 32px;

    .add-header {
      font-size: 18px;
      font-weight: 500;
      color: #000;
      padding: 22px 0 0 26px;
    }

    .add-form-box {
      width: 80%;
      margin: 24px auto;
    }

    .idmanage-tips {
      height: 108px;
      background: #e6fffb;
      border: 1px solid #87e8de;
      margin-bottom: 32px;
      padding: 10px 16px;

      .tips-header {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        font-weight: 600;

        .tips-left {
          display: flex;
          align-items: center;

          .tips-title {
            width: 14px;
            height: 14px;
            background-image: url('/@/assets/images/views/idmanage/tips.png');
            margin-right: 3px;
          }
        }

        .tip-close {
          cursor: pointer;
        }
      }

      .tips-content {
        font-size: 14px;
        font-weight: 400;
        color: #000;
        line-height: 22px;
      }
    }

    .idmanage-container {
      padding: 0 70px;
      margin-top: 40px;

      .iframe {
        width: 100%;
      }
    }
  }
</style>
